package max.ta.data.access;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import max.ta.data.entity.StockQuote;

import org.apache.log4j.Logger;

public class StockeQuoteCSVLoader
	implements CSVDataLoader<StockQuote> {

    private static final Logger logger = Logger.getLogger(StockeQuoteCSVLoader.class);
    private static final int DEAULT_LINE_NUMBER = 6 * 30;

    @Override
    public List<StockQuote> load(File csvFile) throws IOException {
	return load(csvFile, DEAULT_LINE_NUMBER);
    }

    @Override
    public List<StockQuote> load(File csvFile, int lineNumber) throws IOException {
	logger.info(">>> Loading data from CSV file :  " + csvFile.getAbsolutePath());
	List<StockQuote> quotes = new ArrayList<StockQuote>();
	BufferedReader in = null;
	try {
	    in = new BufferedReader(new FileReader(csvFile));
	    String line;
	    String title = in.readLine();
	    logger.debug(title);
	    while ((line = in.readLine()) != null) {
		try {
		    StockQuote quote = readLine(line);
		    quotes.add(quote);
		    if (quotes.size() == lineNumber) {
			break;
		    }
		} catch (ParseException e) {
		    logger.error(ParseException.class.getName() + " : " + e.getMessage());
		} catch (NumberFormatException e) {
		    logger.error(NumberFormatException.class.getName() + " : " + e.getMessage());
		}
	    }
	} finally {
	    if (in != null) {
		in.close();
	    }
	}
	return quotes;
    }

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    // -------------------------------------------------------------
    // Date | Open | High | Low | Close | Volume | Adj. Close
    // -------------------------------------------------------------
    private StockQuote readLine(String str) throws ParseException {
	str = str.replace(" ", "");
	String tokens[] = str.split(",");
	StockQuote quote = new StockQuote();
	String date = tokens[0];
	quote.setDate(DATE_FORMAT.parse(date));
	quote.setOpen(Double.valueOf(tokens[1]));
	quote.setHigh(Double.valueOf(tokens[2]));
	quote.setLow(Double.valueOf(tokens[3]));
	quote.setClose(Double.valueOf(tokens[4]));
	quote.setVolume(Double.valueOf(tokens[5]));
	quote.setAdjecentClose(Double.valueOf(tokens[6]));
	return quote;
    }
}
